#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import re
import sys
import subprocess
import argparse
from data.progress import await_task
from data.get_rime_version import get_rime_version

val_format = "{}	{}	10\n"
table_symbol = '\t'
def_separated_row = "...\n"

user_home = os.path.expanduser("~")

def _get_user_rime_dir():
    # system_type = platform.system()
    if sys.platform.startswith("linux"):
        pass
    elif sys.platform.startswith("win"):
        return os.path.join(user_home, "AppData", "Roaming", "Rime")
    else:
        print("不支持系统")
    raise Exception("不支持系统，即不知道这系统rime的用户路径！")

def _get_rime_exec_dir():
    rime_version = get_rime_version()
    if sys.platform.startswith("linux"):
        pass
    elif sys.platform.startswith("win"):
        return f'C:/Program Files/Rime/weasel-{rime_version}'
    else:
        print("不支持系统")
    raise Exception("不支持系统，即不知道这系统rime的安装路径！")

def _get_weasel_deployer_path():
    if sys.platform.startswith("win"):
        return os.path.join(_get_rime_exec_dir(), 'WeaselDeployer.exe')
    else:
        print("不支持系统")
    raise Exception("不支持系统，即不知道这系统rime的安装路径！")
    

rime_path = _get_user_rime_dir()
local_path = os.path.join(rime_path, "local")

rime_apply = _get_weasel_deployer_path()

def add_wubi_code_dict(terms: str):
    cn_terms = _filter_non_chinese(terms)
    # 1. 获取 单字的 code 映射
    one_word_path = os.path.join(local_path, "one_word.dict.yaml")
    code_map = _dict_yaml_2_map(one_word_path)
    # 2. 拆分 cn_terms ，得到 四码
    str_len = len(cn_terms)
    if str_len == 1:
        print("不支持单字！")
        return
    elif str_len == 2:
        code_key = code_map[cn_terms[0]][0:2] + code_map[cn_terms[1]][0:2]
    elif str_len == 3:
        code_key = code_map[cn_terms[0]][0] + code_map[cn_terms[1]][0] + code_map[cn_terms[2]][0:2]
    else:
        temp = cn_terms[0:3] + cn_terms[-1]
        code_key = ''.join([code_map[item][0] for item in temp])

    join = os.path.join(local_path, "local_auto.dict.yaml")
    text_val = val_format.format(terms, code_key)
    # 读取文件的所有行
    with open(join, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    if def_separated_row not in lines:
        lines.append(def_separated_row)

    lines.append(text_val)

    with open(join, "w", encoding='utf-8') as yaml:
        yaml.writelines(lines)


def _dict_yaml_2_map(yaml_path):
    # 读取文件的所有行
    with open(yaml_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    if def_separated_row not in lines:
        return {}
    index = lines.index(def_separated_row)
    lines = lines[index + 1:]

    return {item.split(table_symbol)[0]: item.split(table_symbol)[1] for item in lines
            if not item.startswith('#') and item != "\n"}


def _filter_non_chinese(text):
    # 使用正则表达式去除非中文字符
    result = re.sub(r'[^\u4e00-\u9fa5]', '', text)
    return result


def comp_dict_yaml_diff(org_file: str, new_file: str, is_change=False):
    """
    比较 源文件中 没有的 目标文件 的词组
    :param org_file: 源文件
    :param new_file: 目标文件
    :param is_change:
    :return:
    """
    if is_change:
        org_file, new_file = new_file, org_file
    org_yaml = os.path.join(local_path, org_file)
    new_yaml = os.path.join(local_path, new_file)
    map_fict = _dict_yaml_2_map(org_yaml)
    is_open = False
    temp_list = []
    with open(new_yaml, 'r', encoding='utf-8') as file:
        for line in file:
            if is_open or (is_open := (def_separated_row == line)):
                split = line.split(table_symbol)
                if map_fict.get(split[0]) is None:
                    temp_list.append(line)

    with open(os.path.join(local_path, 'temp.comparison.yaml'), 'w', encoding='utf-8') as file:
        file.writelines(temp_list)

def ref_rime():
    print('\n🔜  === 重新部署 Rime 最新配置 ===')
    try:
        result = await_task(lambda: subprocess.run([rime_apply, "/deploy"], capture_output=True, text=True, encoding="utf-8"))
        if result.returncode == 0:
            print("\n✅  » Rime 部署成功")
            print(result.stdout)
        else:
            print("🚫  » Rime 部署失败")
            print(result.stderr)
    except Exception as e:
        print(f"执行部署命令时出错: {e}")

if __name__ == '__main__':
    # sys.argv
    # print(sys.argv)
    parser = argparse.ArgumentParser(description="参数.")
    parser.add_argument('--type', type=str, help='类型，默认 add_dict', default="add_dict")
    args = parser.parse_args()
    if args.type == "add_dict":
        loop_txt = "请输入自定义词组："
        user_input = input(loop_txt)
        add_wubi_code_dict(user_input)
        ref_rime()
    elif args.type == "1":
        # comp_dict_yaml_diff("uiuf21.dict.yaml", "D:/Downloads/五笔/sehk43.dict.yaml")
        # comp_dict_yaml_diff("uiuf21.dict.yaml", "D:/Downloads/五笔/sedq60.dict.yaml")
        comp_dict_yaml_diff("gt86.dict.yaml", "gt091.dict.yaml")
        # comp_dict_yaml_diff("one_word.dict.yaml", "temp.yaml", True)
    elif args.type == "r":
        ref_rime()
